import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import HomeView from '../views/HomeView.vue'
import IndexView from '../views/IndexView/IndexView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    children: [
      {
        path: '',
        name: 'Index',
        component: IndexView,
        meta: {
          auth: true,
        }
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('../views/CartView/CartView.vue')
      }
    ]
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue'),
    meta: {
      auth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView/LoginView.vue')
  }
]

const router = new VueRouter({
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {
  const token = store.state.token;

  if (to.meta.auth) {
    if (token) {
      next();
    } else {
      next('/login');
    }
  } else {
    next();
  }
})

export default router
